﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace SalaryChannel.Web
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UserService : ServiceAuthRoot, IUserService
    {
        public UserInfoEntity Login(string UserID, string Pwd)
        {
            try
            {
                Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from p in context.VW_UserWithChannel
                                where p.UserID == UserID
                                where p.Password == Pwd
                                where p.IsDel == '0'
                                select p;
                    if (query.Any())
                    {
                        ///成功
                        VW_UserWithChannel UWC = query.First();
                        UserInfoEntity userInfo = new UserInfoEntity
                        {
                            ChannelID = UWC.ChannelID,
                            ChannelName = UWC.ChannelName,
                            CountyCode = UWC.CountyCode,
                            Email = UWC.Email,
                            Password = UWC.Password,
                            Tel = UWC.Tel,
                            UserID = UWC.UserID,
                            UserName = UWC.UserName,
                            IsDel = UWC.IsDel,
                            DistrictID = UWC.DistrictID,
                            DistrictName = UWC.DistrictName,
                            CityCode=UWC.CityCode,
                            Postcode=UWC.Postcode,
                            ChannelTel=UWC.ChannelTel,
                            Address=UWC.Address,
                            Chief =UWC.Chief,
                            ProviderID=(short)UWC.Provider_ID.Value
                        };
                        var auth = from q in context.User_Auth
                                   where q.User_ID == UserID
                                   select q.Auth_ID;

                        if (auth.Any())
                        {
                            userInfo.Auths = auth.ToArray();
                        }
                        else
                        {
                            userInfo.Auths = new int[] { -1 };
                        }
                        return userInfo;

                    }
                    return new UserInfoEntity { UserID = "-1" };
                }
            }
            catch (Exception e)
            {
                LogManager.Write(UserID + "--" + HttpContext.Current.Request.UserHostAddress
                    + "-- 登录失败--" + e.Message);
                return null;//发生异常
            }
        }




        public int ChangePwd(string UserID, string OldPwd, string NewPwd, bool isAdmin, string OPID)
        {
            try
            {
                Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    if (isAdmin)
                    {
                        var pwd = from q in context.UserInfor
                                  where q.User_ID == UserID
                                  where q.IsDel == '0'
                                  select q;
                        if (!pwd.Any())
                        {
                            return 3;//用户不存在
                        }
                        pwd.First().Password = NewPwd;
                        pwd.First().UpdateID = OPID;
                        pwd.First().UpdateTime = DateTime.Now;
                    }
                    else
                    {
                        var query = from p in context.UserInfor
                                    where p.User_ID == UserID
                                    where p.Password == OldPwd
                                    select p;

                        if (!query.Any())
                        {
                            //原密码不正确
                            return 1;
                        }
                        query.First().Password = NewPwd;
                        query.First().UpdateID = OPID;
                        query.First().UpdateTime = DateTime.Now;
                    }
                    context.SubmitChanges();
                    return 0;
                }
            }
            catch (Exception e)
            {
                LogManager.Write("修改密码失败:" + UserID + "--" + e.Message + "--" + HttpContext.Current.Request.UserHostAddress);
                return 2;//发生异常
            }

        }



        public List<VW_UserWithChannel> QueryUserInforByID(string UserID, string UserName)
        {
            try
            {
                Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    if (!string.IsNullOrEmpty(UserID)
                        && !string.IsNullOrEmpty(UserName))
                    {
                        return (from q in context.VW_UserWithChannel
                                where q.UserID == UserID
                                where q.UserName.Contains(UserName)
                                select q).ToList();
                    }
                    else if (!string.IsNullOrEmpty(UserID))
                    {
                        return (from q in context.VW_UserWithChannel
                                where q.UserID == UserID
                                select q).ToList<VW_UserWithChannel>();
                    }
                    else
                    {
                        return (from q in context.VW_UserWithChannel
                                where q.UserName.Contains(UserName)
                                select q).ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("QueryUserInforByID:" + UserID + "--" + ex.Message + "--" + HttpContext.Current.Request.UserHostAddress);
                return null;
            }
        }


        public List<VW_UserWithChannel> QueryUserInforByChannel(string ChannelID, string ChannelName)
        {
            try
            {
                Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    if (!string.IsNullOrEmpty(ChannelID)
                        && !string.IsNullOrEmpty(ChannelName))
                    {
                        return (from q in context.VW_UserWithChannel
                                where q.ChannelID == ChannelID
                                where q.ChannelName.Contains(ChannelName)
                                select q).ToList();

                    }
                    else if (!string.IsNullOrEmpty(ChannelID))
                    {
                        return (from q in context.VW_UserWithChannel
                                where q.ChannelID == ChannelID
                                select q).ToList();
                    }
                    else
                    {
                        return (from q in context.VW_UserWithChannel
                                where q.ChannelName.Contains(ChannelName)
                                select q).ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("QueryUserInforByChannel:" + ChannelName + "--" + ChannelID + "--" + ex.Message + "--" + HttpContext.Current.Request.UserHostAddress);
                return null;
            }
        }

        public string DeleteUser(string UserID,string OPID)
        {
            try
            {
                Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from p in context.UserInfor
                                where p.User_ID == UserID
                                select p;
                    if (query.Any())
                    {
                        query.First().IsDel = '1';
                        query.First().UpdateTime = DateTime.Now;
                        query.First().UpdateID = OPID;

                        context.SubmitChanges();

                        return "true";
                    }
                    return "此用户不存在";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string AddUser(UserInfor NewUser)
        {
            try
            {
                Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {

                    context.UserInfor.InsertOnSubmit(NewUser);

                    context.SubmitChanges();
                    return "true";
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("FK_UserInfor_ChannelAccount"))
                {
                    return "渠道不存在";
                    
                }
                LogManager.Write("UserService.AddUser:"+ex.Message);
                return ex.Message;
            }
        }

        public bool UpdateUser(UserInfor newUser)
        {
            try
            {
                Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.UserInfor
                                where q.User_ID == newUser.User_ID
                                select q;
                    if (query.Any())
                    {
                        query.First().UserName = newUser.UserName;
                        query.First().Channel_ID = newUser.Channel_ID;
                        query.First().AdminLevel = newUser.AdminLevel;
                        query.First().Password = newUser.Password;
                        query.First().Tel = newUser.Tel;
                        query.First().Email = newUser.Email;
                        query.First().IsDel = newUser.IsDel;
                        query.First().UpdateTime = DateTime.Now;
                        query.First().UpdateID = newUser.UpdateID;
                        context.SubmitChanges();
                        return true;
                    }

                    return false;
                }
            }
            catch (Exception ex)
            {
                LogManager.Write(ex.Message);
                return false;
            }
        }

        public bool UpdateTelEmail(string Tel, string Email, string UserID)
        {
            try
            {
                this.Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.UserInfor
                                where q.User_ID == UserID
                                select q;
                    if (query.Any())
                    {
                        query.First().Email = Email;
                        query.First().Tel = Tel;
                        context.SubmitChanges();
                        return true;
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("UserService.UpdateTelEmail:" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 通过AM密码找回本系统密码
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="AMPwd"></param>
        /// <returns></returns>
        public string GetMyPwd(string UserID, string AMPwd)
        {

            try
            {



                using (SqlConnection con = new SqlConnection(this.AMSqlString))
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = string.Format(
                        "select top 1 cn_password from tn_sys_em_user where cn_login=\'{0}\'",
                        UserID, AMPwd);
                    con.Open();
                    object ret = cmd.ExecuteScalar();
                    if (ret == null || ret.ToString() == string.Empty)
                    {

                        return "AM用户名不存在";
                    }
                    else if (ret.ToString() != AMPwd)
                    {
                        return "AM密码不正确";
                    }
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("UserService.GetMyPwd验证AM密码失败:" + ex.Message);
                return "验证AM密码失败";
            }
            string pwd = string.Empty;
            string e=string.Empty;
            try
            {
                this.Authoricate();

                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.UserInfor
                                where q.User_ID == UserID
                                where q.IsDel == '0'
                                select q;
                    if (!query.Any())
                    {

                        return "用户名不存在";//不是本系统用户
                    }

                    pwd = query.First().Password;
                    e=query.First().Email;
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("UserService.GetMyPwd查询密码失败:" + ex.Message);
                return "查询密码失败";
            }


            try
            {
               // AMSender am = new AMSender();
               // am.SendMsg("天水移动渠道综合支撑系统",
                 //   string.Format("您的密码为：{0}。请妥善保管！", pwd), UserID, null);
                Email.SendEmail("天水移动卖场销售管理系统", this.EmailSender,
                    this.EmailSMTP, this.EmailSenderUser, this.EmailSenderPwd,
                   e,
                    "密码找回", string.Format("您的密码为：{0}。请妥善保管！", pwd), null, "GB2312");

                return "true";
            }
            catch (Exception ex)
            {

                LogManager.Write("UserService.GetMyPwd查询密码失败:" + ex.Message);
                return "发送密码失败";
            }
        }

        public List<UserAuthEntity> GetUserAuth(string UserID)
        {

            try
            {
                this.Authoricate();
                DataTable table = new DataTable("Auths");
                using (SqlConnection con = new SqlConnection(this.SqlString))
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_GetUserAuth";

                    cmd.Parameters.Add(new SqlParameter("@UserID", UserID));
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(table);
                }
                List<UserAuthEntity> authlist = new List<UserAuthEntity>(table.Rows.Count);
                foreach (DataRow row in table.Rows)
                {
                    authlist.Add(new UserAuthEntity
                    {
                        Auth_ID = int.Parse(row["Auth_ID"].ToString()),
                        Auth_Name = row["Auth_Name"].ToString(),
                        Remark = row["Remark"] == null ? string.Empty : row["Remark"].ToString(),
                        User_ID = row["User_ID"] == null ? string.Empty : row["User_ID"].ToString(),
                        Creater = row["Create_ID"] == null || row["Create_ID"].ToString() == string.Empty ? string.Empty : string.Format("[{0}]{1}", row["Create_ID"], row["Create_Name"]),
                        Create_Time = row["Create_Time"] == null ? string.Empty : row["Create_Time"].ToString(),// DateTime.Parse(row["Create_Time"].ToString()).ToString("yyyy-MM-dd hh:mm:ss"),
                        IsChecked = row["IsChecked"].ToString() == "1"
                    });
                }
                return authlist;
            }
            catch (Exception ex)
            {

                LogManager.Write("UserService.GetUserAuth 查询失败:" + ex.Message);
                return null;
            }

        }

        public bool UpdateUserAuth(string CreateUserID, string UserID, int[] Auths)
        {
            try
            {
                this.Authoricate();
                using (SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    List<User_Auth> add = new List<User_Auth>();
                    var owned = from q in context.User_Auth
                                where q.User_ID == UserID && q.Auth_ID != 0
                                select q;
                    if (Auths.Length == 0)
                    {
                        context.User_Auth.DeleteAllOnSubmit(owned.ToList());
                    }
                    else if (!owned.Any())
                    {
                        foreach (int id in Auths)
                        {
                            add.Add(new User_Auth
                            {
                                Auth_ID = id,
                                User_ID = UserID,
                                Create_ID = CreateUserID,
                                Create_Time = DateTime.Now
                            });

                        }
                        context.User_Auth.InsertAllOnSubmit(add);
                    }
                    else
                    {
                        var del = from o in owned
                                  where !Auths.Contains(o.Auth_ID)
                                  select o;
                        if (del.Any())
                        {
                            context.User_Auth.DeleteAllOnSubmit(del.ToList());
                            context.SubmitChanges();
                        }

                        var now = from a in context.User_Auth
                                  where a.User_ID == UserID
                                  select a.Auth_ID;
                        if (now.Any())
                        {
                            foreach (int a in Auths)
                            {
                                if (!now.Contains(a))
                                {
                                    add.Add(new User_Auth
                                    {
                                        Auth_ID = a,
                                        User_ID = UserID,
                                        Create_ID = CreateUserID,
                                        Create_Time = DateTime.Now

                                    });
                                }
                            }
                            context.User_Auth.InsertAllOnSubmit(add);
                        }


                    }

                    context.SubmitChanges();
                    return true;
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("UserService.UpdateUserAuth:" + ex.Message);
                return false;
            }
        }

        public List<string> GetArea(string CityCode)
        {
            try
            {
                this.Authoricate();
                List<string> list = new List<string>();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.CM_Region
                                where q.CityCode == CityCode
                                orderby q.CountyCode
                                select new { AreaCode = q.CountyCode, AreaName = q.CountyName };
                    if (query.Any())
                    {
                        foreach (var a in query)
                        {
                            list.Add(string.Format("[{0}]{1}", a.AreaCode, a.AreaName));
                        }
                    }

                }
                return list;
            }
            catch (Exception ex)
            {
                LogManager.Write("UserService.GetArea:" + ex.Message);
                return null; 
            }
        }

        public List<string> GetDistrict(string AreaCode)
        {
            try
            {
                this.Authoricate();
                List<string> list = new List<string>();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.CM_District
                                where q.Area_Code==AreaCode
                                orderby q.District_ID
                                select new { id = q.District_ID, name = q.District_Name };
                    if (query.Any())
                    {
                        foreach (var a in query)
                        {
                            list.Add(string.Format("[{0}]{1}", a.id, a.name));
                        }
                    }

                }
                return list;
            }
            catch (Exception ex)
            {
                LogManager.Write("UserService.GetDistrict:" + ex.Message);
                return null; 
            }
        }

        public int UpdateChannel(string ID, string Name, string AreaCode, string DistrictID,string OPID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.ChannelAccount
                                where q.Id == ID
                                select q;
                    if (query.Any())
                    {
                        query.First().ChannelName = Name;
                        query.First().CountyCode = AreaCode;
                        query.First().PQ_ID = DistrictID;
                        query.First().Update_ID = OPID;
                        query.First().Update_Time = DateTime.Now;
                    }
                    else
                    {
                        context.ChannelAccount.InsertOnSubmit(new ChannelAccount
                        {
                            Id = ID,
                            ChannelName = Name,
                            CountyCode = AreaCode,
                            PQ_ID = DistrictID,
                            Create_ID = OPID,
                            Create_Time = DateTime.Now

                        });
                    }
                    context.SubmitChanges();
                    return 0;

                }
            }
            catch (Exception ex)
            {
                LogManager.Write("UserService.GetDistrict:" + ex.Message);
                return -1 ;
            }
        }




        public List<VW_ChannelWithDistrict> GetChannel(string id, string name)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.VW_ChannelWithDistrict
                                where (q.Id == id || string.IsNullOrEmpty(id))
                                && q.ChannelName.Contains(name)
                                select q;
                    if (query.Any())
                    {
                        return query.ToList();
                    }

                    return new List<VW_ChannelWithDistrict>();

                }
            }
            catch (Exception ex)
            {
                LogManager.Write("UserService.GetChannel:" + ex.Message);
                return null;
            }
        }

        #region IUserService 成员


        public string GetPwdByEmail(string UserID)
        {
            try
            {
                this.Authoricate();
                using (DataClassesQueryDataContext context = new DataClassesQueryDataContext())
                {
                    var query = from q in context.UserInfor
                                where q.User_ID == UserID
                                select q;
                    if (query.Any())
                    {

                        UserInfor u = query.First();
                        if (u.IsDel == '1')
                        {
                            return "此用户名(" + UserID + ")已停用";
                        }
                        if (string.IsNullOrWhiteSpace(u.Email))
                        {
                            return "此用户名(" + UserID + ")邮件地址不存在";
                        }

                        if (this.SendEmailDirectly("渠道综合支撑系统密码找回邮件，请误回复",
                            string.Format("您的登录密码为[{0}]，请妥善保管！", u.Password), u.Email))
                        {
                            return string.Empty;
                        }
                        else
                        {
                            return "向指定的地址发送邮件失败";
                        }


                    }
                    
                    return "此用户名("+UserID+")不存在";

                }
            }
            catch (Exception ex)
            {
                LogManager.Write("UserService.GetPwdByEmail:" + ex.Message);
                return ex.Message;
            }
        }

        #endregion
    }


    [Serializable]
    public class UserInfoEntity
    {
        public string UserID;

        public string UserName;

        //public int AdminLevel;

        public string Password;

        public string ChannelID;

        public string ChannelName;

        public string CountyCode;

        public string DistrictID;

        public string DistrictName;

        public string Tel;

        public string Email;

        public char IsDel;

        public int[] Auths;
        public string CityCode;

        public string ChannelTel;
        public string Address;
        public string Postcode;
        public string Chief;
        public short ProviderID;


        public UserInfoEntity()
        {
        }
    }

    [Serializable]
    public class UserAuthEntity
    {
        public int Auth_ID;
        public string Auth_Name;
        public string Remark;
        public string User_ID;
        public string Creater;
        public string Create_Time;
        public bool IsChecked;
       
       
    }
}